<template>
  <div class="ai-home">
    <!-- 用户头像下拉菜单 -->
    <div class="user-avatar-container">
      <el-dropdown @command="handleCommand" trigger="hover" class="avatar-dropdown">
        <div class="avatar-wrapper">
          <img :src="userStore.avatar" class="user-avatar" />
          <span class="user-nickname">{{ userStore.nickName }}</span>
          <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile">
              <el-icon><User /></el-icon>
              个人中心
            </el-dropdown-item>
            <el-dropdown-item command="logout" divided>
              <el-icon><SwitchButton /></el-icon>
              退出登录
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    
    <!-- 网站标题和介绍 -->
    <div class="hero-section">
      <div class="hero-content">
        <h1 class="hero-title">
          AI 生成应用平台
        </h1>
        <p class="hero-subtitle">与 AI 对话轻松创建应用和网站</p>
        
        <!-- 用户提示词输入框 -->
        <div class="prompt-input-section">
          <div class="input-container">
            <el-input
              v-model="userPrompt"
              type="textarea"
              :rows="5"
              placeholder="输入你的想法..."
              class="prompt-input"
            />
            <el-button type="primary" size="large" @click="createApp" :loading="creating" class="create-btn">
              <el-icon><Plus /></el-icon>
              创建应用
            </el-button>
          </div>
        </div>

        <!-- 快捷模板按钮 -->
        <div class="template-buttons">
          <el-button 
            v-for="template in templates" 
            :key="template.name"
            @click="selectTemplate(template.prompt)"
            class="template-btn"
          >
            {{ template.name }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 我的应用列表 -->
    <div class="section">
      <div class="section-header">
        <h2>我的作品</h2>
        <el-input
          v-model="myAppQuery.appName"
          placeholder="搜索我的应用"
          style="width: 200px"
          clearable
          @keyup.enter="loadMyApps"
        >
          <template #append>
            <el-button @click="loadMyApps" icon="Search" />
          </template>
        </el-input>
      </div>
      
      <div v-loading="myAppsLoading" class="app-grid my-apps-grid">
        <div 
          v-for="app in myApps" 
          :key="app.id" 
          class="app-card"
          @click="goToChat(app.id)"
        >
          <div class="app-cover">
            <img v-if="app.cover" :src="app.cover" :alt="app.appName" />
            <div v-else class="default-cover">
              <el-icon size="40"><Document /></el-icon>
            </div>
          </div>
          <div class="app-info">
            <h3 class="app-name">{{ app.appName || '未命名应用' }}</h3>
            <p class="app-time">创建于 {{ formatTime(app.createTime) }}</p>
            <div class="app-type-badge">
              <el-tag type="primary">
                <dict-tag :options="generation_type" :value="app.codeGenType" size="small" />
              </el-tag>
            </div>
          </div>
          <div class="app-actions" @click.stop>
            <el-dropdown trigger="click">
              <el-button text>
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="editApp(app.id)">
                    <el-icon><Edit /></el-icon>编辑
                  </el-dropdown-item>
                  <el-dropdown-item @click="deleteMyApp(app)" divided>
                    <el-icon><Delete /></el-icon>删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>

      <div class="pagination-wrapper" v-if="myAppTotal > 0">
        <el-pagination
          v-model:current-page="myAppQuery.pageNum"
          v-model:page-size="myAppQuery.pageSize"
          :total="myAppTotal"
          :page-sizes="[6, 12, 24]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadMyApps"
          @current-change="loadMyApps"
        />
      </div>
    </div>

    <!-- 精选应用列表 -->
    <div class="section">
      <div class="section-header">
        <h2>精选案例</h2>
        <el-input
          v-model="goodAppQuery.appName"
          placeholder="搜索精选应用"
          style="width: 200px"
          clearable
          @keyup.enter="loadGoodApps"
        >
          <template #append>
            <el-button @click="loadGoodApps" icon="Search" />
          </template>
        </el-input>
      </div>
      
      <div v-loading="goodAppsLoading" class="app-grid">
        <div 
          v-for="app in goodApps" 
          :key="app.id" 
          class="app-card featured"
          @click="goToChat(app.id)"
        >
          <div class="app-cover">
            <img v-if="app.cover" :src="app.cover" :alt="app.appName" />
            <div v-else class="default-cover">
              <el-icon size="40"><Star /></el-icon>
            </div>
          </div>
          <div class="app-info">
            <h3 class="app-name">{{ app.appName || '精选应用' }}</h3>
            <p class="app-desc">{{ app.initPrompt || '暂无描述' }}</p>
            <div class="app-author" v-if="app.user">
              <img :src="app.user.avatar || '/src/assets/images/profile.jpg'" :alt="app.user.nickName" class="author-avatar" />
              <span class="author-name">{{ app.user.nickName || app.user.userName }}</span>
            </div>
            <div class="app-type-badge">
              <el-tag type="primary">
                <dict-tag :options="generation_type" :value="app.codeGenType" size="small" />
              </el-tag>
            </div>
          </div>
          <div class="featured-badge">
            <el-icon><Star /></el-icon>
            精选
          </div>
        </div>
      </div>

      <div class="pagination-wrapper" v-if="goodAppTotal > 0">
        <el-pagination
          v-model:current-page="goodAppQuery.pageNum"
          v-model:page-size="goodAppQuery.pageSize"
          :total="goodAppTotal"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadGoodApps"
          @current-change="loadGoodApps"
        />
      </div>
    </div>
  </div>
</template>

<script setup name="AiHome">
import { ref, reactive, onMounted, getCurrentInstance, toRaw } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { Plus, Document, MoreFilled, Edit, Delete, Star, Search, ArrowDown, User, SwitchButton } from '@element-plus/icons-vue'
import { createUserApp, getMyAppList, getGoodAppList, deleteUserApp } from '@/api/ai/app'
import { getUserProfile } from '@/api/system/user'
import { parseTime } from '@/utils/ruoyi'
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance()
const { generation_type } = proxy.useDict('generation_type')
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const userPrompt = ref('')
const creating = ref(false)

// 我的应用数据
const myApps = ref([])
const myAppsLoading = ref(false)
const myAppTotal = ref(0)
const myAppQuery = reactive({
  pageNum: 1,
  pageSize: 6,
  appName: ''
})

// 精选应用数据
const goodApps = ref([])
const goodAppsLoading = ref(false)
const goodAppTotal = ref(0)
const goodAppQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  appName: ''
})

// 快捷模板
const templates = ref([
  { name: '波普风电商页面', prompt: '创建一个波普风格的电商产品页面，包含商品展示、购买按钮和用户评价' },
  { name: '企业网站', prompt: '设计一个现代化的企业官网，包含公司介绍、产品服务和联系方式' },
  { name: '电商运营后台', prompt: '开发一个电商运营管理后台，包含订单管理、商品管理和数据统计' },
  { name: '暗黑主题社区', prompt: '构建一个暗黑主题的技术社区网站，支持文章发布和用户互动' }
])

// 创建应用
const createApp = async () => {
  if (!userPrompt.value.trim()) {
    proxy.$modal.msgWarning('请输入应用描述')
    return
  }
  
  creating.value = true
  try {
    const response = await createUserApp({ initPrompt: userPrompt.value })
    if (response.code === 200) {
      proxy.$modal.msgSuccess('应用创建成功')
      // 跳转到对话页面，标记为新创建的应用
      router.push(`/ai/chat/${response.data}?new=true`)
    }
  } catch (error) {
    console.error('创建应用失败:', error)
    proxy.$modal.msgError('创建应用失败')
  } finally {
    creating.value = false
  }
}

// 选择模板
const selectTemplate = (prompt) => {
  userPrompt.value = prompt
}

// 加载我的应用
const loadMyApps = async () => {
  console.log('loadMyApps called with params:', myAppQuery)
  myAppsLoading.value = true
  try {
    const response = await getMyAppList(toRaw(myAppQuery))
    console.log('getMyAppList response:', response)
    if (response.code === 200) {
      myApps.value = response.rows || []
      myAppTotal.value = response.total || 0
      console.log('My apps loaded:', myApps.value.length, 'Total:', myAppTotal.value)
    }
  } catch (error) {
    console.error('加载我的应用失败:', error)
  } finally {
    myAppsLoading.value = false
  }
}

// 加载精选应用
const loadGoodApps = async () => {
  console.log('loadGoodApps called with params:', goodAppQuery)
  goodAppsLoading.value = true
  try {
    const response = await getGoodAppList(toRaw(goodAppQuery))
    console.log('getGoodAppList response:', response)
    if (response.code === 200) {
      goodApps.value = response.rows || []
      goodAppTotal.value = response.total || 0
      console.log('Good apps loaded:', goodApps.value.length, 'Total:', goodAppTotal.value)
    }
  } catch (error) {
    console.error('加载精选应用失败:', error)
  } finally {
    goodAppsLoading.value = false
  }
}

// 跳转到对话页面
const goToChat = (appId) => {
  router.push(`/ai/chat/${appId}`)
}

// 编辑应用
const editApp = (appId) => {
  router.push(`/ai/app/edit/${appId}`)
}

// 删除应用
const deleteMyApp = async (app) => {
  try {
    await proxy.$modal.confirm(`确定要删除应用"${app.appName || '未命名应用'}"吗？`)
    const response = await deleteUserApp({ id: app.id })
    if (response.code === 200) {
      proxy.$modal.msgSuccess('删除成功')
      loadMyApps()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除应用失败:', error)
      proxy.$modal.msgError('删除应用失败')
    }
  }
}

// 格式化时间
const formatTime = (time) => {
  return parseTime(time, '{y}-{m}-{d}')
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/ai/profile')
      break
    case 'logout':
      logout()
      break
    default:
      break
  }
}

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.logOut().then(() => {
      location.href = '/ai/home'
    })
  }).catch(() => {})
}

// 页面加载时获取数据
onMounted(() => {
  loadMyApps()
  loadGoodApps()
})
</script>

<style scoped>
.ai-home {
  min-height: 100vh;
  background: 
    radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.15) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(120, 219, 226, 0.15) 0%, transparent 50%),
    linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 30%, #667eea 70%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.ai-home::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.05'%3E%3Ccircle cx='30' cy='30' r='1.5'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E") repeat;
  pointer-events: none;
}

/* 用户头像组件样式 */
.user-avatar-container {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1000;
}

.avatar-dropdown {
  cursor: pointer;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 25px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.avatar-wrapper:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 8px;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.user-nickname {
  color: white;
  font-size: 14px;
  font-weight: 500;
  margin-right: 6px;
}

.dropdown-icon {
  color: white;
  font-size: 12px;
  transition: transform 0.3s ease;
}

.avatar-dropdown:hover .dropdown-icon {
  transform: rotate(180deg);
}

.hero-section {
  padding: 80px 20px 60px;
  text-align: center;
  background: transparent;
  color: white;
  position: relative;
  z-index: 1;
}

.hero-content {
  max-width: 800px;
  margin: 0 auto;
}

.hero-title {
  font-size: 3.5rem;
  font-weight: 700;
  margin-bottom: 20px;
  line-height: 1.2;
}

.logo-icon {
  color: #ffd700;
}

.hero-subtitle {
  font-size: 1.5rem;
  margin-bottom: 40px;
  opacity: 0.9;
}

.prompt-input-section {
  background: transparent;
  margin-bottom: 30px;
}

.input-container {
  position: relative;
}

.prompt-input {
  width: 100%;
}

.prompt-input :deep(.el-textarea__inner) {
  background: rgba(255, 255, 255, 0.95);
  border: none;
  border-radius: 20px;
  font-size: 16px;
  line-height: 1.6;
  padding: 25px;
  padding-bottom: 80px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  min-height: 220px;
}

.prompt-input :deep(.el-textarea__inner):focus {
  border-color: rgba(102, 126, 234, 0.5);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
  outline: none;
}

.create-btn {
  position: absolute;
  bottom: 20px;
  right: 20px;
  padding: 12px 30px;
  font-size: 16px;
  border-radius: 25px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
  z-index: 10;
  overflow: hidden;
}

.create-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.create-btn:hover::before {
  left: 100%;
}

.create-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 35px rgba(102, 126, 234, 0.5);
}

.template-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

.template-btn {
  background: rgba(255, 255, 255, 0.15);
  border: 1px solid rgba(255, 255, 255, 0.25);
  color: white;
  border-radius: 25px;
  padding: 10px 24px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  backdrop-filter: blur(10px);
  font-size: 14px;
  font-weight: 500;
}

.template-btn:hover {
  background: rgba(255, 255, 255, 0.25);
  border-color: rgba(255, 255, 255, 0.4);
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(255, 255, 255, 0.1);
}

.section {
  padding: 60px 20px;
  max-width: 1200px;
  margin: 0 auto;
}


.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.section-header h2 {
  font-size: 2rem;
  color: white;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.app-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.my-apps-grid {
  max-height: 560px; /* 限制为大约2行的高度 */
  overflow-y: auto;
  padding-right: 10px; /* 为滚动条留出空间 */
}

.my-apps-grid::-webkit-scrollbar {
  width: 8px;
}

.my-apps-grid::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.my-apps-grid::-webkit-scrollbar-thumb {
  background: rgba(102, 126, 234, 0.3);
  border-radius: 4px;
  transition: background 0.3s ease;
}

.my-apps-grid::-webkit-scrollbar-thumb:hover {
  background: rgba(102, 126, 234, 0.5);
}

.app-card {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  cursor: pointer;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.app-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 20px 40px rgba(102, 126, 234, 0.15);
  border-color: rgba(102, 126, 234, 0.3);
  background: rgba(255, 255, 255, 0.95);
}

.app-card.featured {
  border: 2px solid rgba(255, 215, 0, 0.6);
  background: linear-gradient(135deg, rgba(255, 249, 230, 0.9) 0%, rgba(255, 255, 255, 0.9) 100%);
  backdrop-filter: blur(15px);
}

.app-cover {
  height: 160px;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 15px;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.app-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-cover {
  color: #999;
}

.app-info h3 {
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.app-time, .app-desc {
  font-size: 0.9rem;
  color: #666;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.app-author {
  display: flex;
  align-items: center;
  margin-top: 8px;
  gap: 6px;
}

.author-avatar {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid rgba(0, 0, 0, 0.1);
  object-fit: cover;
}

.author-name {
  font-size: 0.8rem;
  color: #888;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.app-actions {
  position: absolute;
  top: 15px;
  right: 15px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.app-card:hover .app-actions {
  opacity: 1;
}

.featured-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background: linear-gradient(45deg, #ffd700, #ffed4a);
  color: #333;
  padding: 5px 10px;
  border-radius: 0 12px 0 12px;
  font-size: 0.8rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 4px;
}

.app-type-badge {
  position: absolute;
  bottom: 15px;
  right: 15px;
  z-index: 10;
  color: #333;
}

.app-type-badge .el-tag {
  font-size: 0.75rem;
  padding: 4px 8px;
  border-radius: 12px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .hero-title {
    font-size: 2.5rem;
  }
  
  .hero-subtitle {
    font-size: 1.2rem;
  }
  
  .prompt-input-section {
    padding: 20px;
  }
  
  .template-buttons {
    gap: 10px;
  }
  
  .section {
    padding: 40px 15px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
  }
  
  .app-grid {
    grid-template-columns: 1fr;
  }
}
</style>
